package com.demo.ohos_zblibrary.application;

import com.demo.ohos_zblibrary.manager.DataManager;
import com.demo.ohos_zblibrary.model.User;

import ohos.aafwk.ability.AbilityPackage;
import zuo.biao.library.manager.HttpManager;
import zuo.biao.library.util.StringUtil;

import java.util.Optional;

/**
 * Demo Application
 */
public class DemoApplication extends AbilityPackage {
    /**
     * 上下文
     */
    public static DemoApplication context;

    private static final String TAG = "DemoApplication";

    /**
     * 实例化
     * @return 实
     */
    public static DemoApplication getInstance() {
        return context;
    }

    @Override
    public void onInitialize() {
        super.onInitialize();
        context = this;
    }

    /**
     * 获取当前用户id
     * @return long
     */
    public long getCurrentUserId() {
        currentUser = getCurrentUser();
        return currentUser == null ? 0 : currentUser.getId();
    }

    /**
     * 获取当前用户phone
     * @return String
     */
    public String getCurrentUserPhone() {
        currentUser = getCurrentUser();
        return currentUser == null ? null : currentUser.getPhone();
    }

    private static User currentUser = null;

    private User getCurrentUser() {
        if (currentUser == null) {
            currentUser = DataManager.getInstance().getCurrentUser();
        }
        return currentUser;
    }

    private void saveCurrentUser(User user) {
        if (user == null) {
            return;
        }
        if (user.getId() <= 0 && StringUtil.isNotEmpty(user.getName(), true) == false) {
            return;
        }

        currentUser = user;
        DataManager.getInstance().saveCurrentUser(currentUser);
    }

    private void logout() {
        currentUser = null;
        DataManager.getInstance().saveCurrentUser(currentUser);
    }

    /**
     * 判断是否为当前用户
     * @param userId u
     * @return boolean
     */
    public boolean isCurrentUser(long userId) {
        return DataManager.getInstance().isCurrentUser(userId);
    }

    private boolean isLoggedIn() {
        return getCurrentUserId() > 0;
    }
}
